package cn.bestick.cblog.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.bestick.cblog.dmo.User;
import cn.bestick.cblog.dto.UserDto;
import cn.bestick.cblog.service.UserService;
import cn.bestick.cblog.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		HttpSession session = request.getSession();
		String action = request.getParameter("action");
		if ("quit".equals(action)) {
			session.invalidate();
			response.sendRedirect("home");
		} else {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String remember = request.getParameter("remember");

			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			UserDto currentUser = userService.login(user);
			if (currentUser == null) {
				request.setAttribute("user", user);
				request.setAttribute("error", "用户名或密码错误");
				request.getRequestDispatcher("login.jsp").forward(request,
						response);
			} else {
				if ("remember-me".equals(remember)) {
					rememberMe(username, password, response);
				}
				session.setAttribute("currentUser", currentUser);
				if (currentUser.getState() == 0) {
					response.sendRedirect("home");
				} else {
					response.sendRedirect("manage");
				}
			}
		}
	}

	private void rememberMe(String username, String password,
			HttpServletResponse response) {
		Cookie user = new Cookie("user", username + "-" + password);
		user.setMaxAge(1 * 60 * 60 * 24 * 7);
		response.addCookie(user);
	}
}
